package com.hfzy.ihk.web.freeswitchManage.biz;

import com.hfzy.ihk.facade.freeswitchManage.enums.GatewayStateEnum;
import com.hfzy.ihk.common.util.string.StringTools;
import com.hfzy.ihk.facade.freeswitchManage.entity.Gateway;
import com.hfzy.ihk.facade.userCenter.entity.UserInfo;
import com.hfzy.ihk.web.freeswitchManage.mapper.GatewayMapper;
import com.hfzy.ihk.web.freeswitchManage.vo.GatewayVo;
import com.hfzy.ihk.web.oauth.client.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Created by YANFA on 2019/3/25.
 */
@Component
public class GatewayInfoBiz {

    @Autowired
    GatewayMapper gatewayMapper ;

    /**
     * 保存
     * @param gatewayVo
     */
    public void saveGateway(GatewayVo gatewayVo){
        if(StringTools.isNotempty(gatewayVo.getId())){
            update(gatewayVo);

        }else{
            insert(gatewayVo);
        }

    }

    /**
     * 插入
     * @param gatewayVo
     */
    private void insert(GatewayVo gatewayVo){
        //判断是否已经存在该设备
        Gateway gateway = gatewayMapper.queryGatewayByNum(gatewayVo.getNum());
        if(gateway!=null){
            throw new IllegalArgumentException("该设备已经存在");
        }
        Gateway _gateway = (Gateway)gatewayVo;
        UserInfo userInfo = UserUtil.getLoginUser();
        if(userInfo!=null){
            _gateway.setCreateUserId(userInfo.getId());
            _gateway.setCreateUserName(userInfo.getName());
        }
        _gateway.setCreateTime(new Date());
        _gateway.setState(GatewayStateEnum.HANG_UP);
        gatewayMapper.insert(_gateway);

    }

    /**
     * 更新
     * @param gatewayVo
     */
    private void update(GatewayVo gatewayVo){
        //判断是否已经存在该设备
        Gateway gateway = gatewayMapper.queryGatewayByNum(gatewayVo.getNum());

        if(gateway!=null&&gatewayVo.getId().intValue()!=gateway.getId().intValue()){
            throw new IllegalArgumentException("该设备已经存在");
        }

        Gateway _gateway = (Gateway)gatewayVo;

        UserInfo userInfo = UserUtil.getLoginUser();
        if(userInfo!=null){
            _gateway.setModUserId(userInfo.getId());
            _gateway.setModUserName(userInfo.getName());
        }

        _gateway.setModTime(new Date());

        gatewayMapper.updateById(_gateway);

    }

    /**
     * 删除
     * @param id
     */
    public void del(Long id){
        gatewayMapper.deleteById(id);

    }
}
